package com.store.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.libs.widget.CWToast;
import com.store.app.broadcast.CompleteService;
import com.store.app.utils.IntentUtils;
import com.store.app.utils.PackageUtils;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 所有Activity的父类
 */
public class BaseActivity extends Activity {
    public static long downLoadId;
    private volatile ProgressDialog mProgressDialog;
    private volatile Toast mToast;

    public String time_String(long first_time) {
        Date date = new Date(first_time * 1000);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }

    @Override
    public void finish() {

        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);

        super.finish();
    }

    public void downLoadPackage(String url) {
//        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//
//        Uri uri = Uri.parse(url);
//        DownloadManager.Request request = new DownloadManager.Request(uri);
//
//        //设置允许使用的网络类型，这里是移动网络和wifi都可以
//        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
//
//        //禁止发出通知，既后台下载，如果要使用这一句必须声明一个权限：android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
//        //request.setShowRunningNotification(false);
//
//        //不显示下载界面
//        request.setVisibleInDownloadsUi(false);
//        /*设置下载后文件存放的位置,如果sdcard不可用，那么设置这个将报错，因此最好不设置如果sdcard可用，下载后的文件        在/mnt/sdcard/Android/data/packageName/files目录下面，如果sdcard不可用,设置了下面这个将报错，不设置，下载后的文件在/cache这个  目录下面*/
//        request.setDestinationInExternalPublicDir("download", "diandong.apk");
//        downLoadId = downloadManager.enqueue(request);


        Intent updataService = new Intent(this, CompleteService.class);
        updataService.putExtra("downloadurl", url);
        startService(updataService);
    }

    public static boolean isDownloadManagerAvailable(Context context) {
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD
                    || context.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == context
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED_USER
                    || context.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == context
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED
                    || context.getPackageManager()
                    .getApplicationEnabledSetting(
                            "com.android.providers.downloads") == context
                    .getPackageManager().COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {

                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    //创建progressDialog
    private void createProgressDialog(String title, String msg) {
        if (mProgressDialog == null || !mProgressDialog.getContext().equals(this)) {
            mProgressDialog = new ProgressDialog(this);
        }
        if (!TextUtils.isEmpty(title)) {
            mProgressDialog.setTitle(title);
        }
        mProgressDialog.setMessage(msg);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//默认样式
    }

    protected void showProgressDialog(String title, String msg) {
        createProgressDialog(title, msg);
        mProgressDialog.setCancelable(true);
        if (isFinishing()) {//在Activity调用了finish()后立即使用AlertDialog将会报错，可能原因是Android系统finish 1个Activity需要一个过程才能完成
            return;
        }
        mProgressDialog.show();
    }

    protected void showProgressDialog(String title, String msg, boolean ifCancel) {
        createProgressDialog(title, msg);
        mProgressDialog.setCancelable(ifCancel);
        mProgressDialog.show();
    }

    protected void dismissProgressDialog() {
        try {
            if (mProgressDialog != null)
                mProgressDialog.dismiss();
        } catch (Exception e) {

        }
    }

    protected void showToast(int msgId) {
        showToast(getString(msgId));
    }

    protected void showToast(int msgId, int duration) {
        showToast(getString(msgId), duration);
    }

    protected void showToast(String msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    protected void showLongToast(String msg) {
        showToast(msg, Toast.LENGTH_LONG);
    }

    protected void showToast(String msg, int duration) {
        if (msg.contains("本地网络")) {
            CWToast.makeText(this, "请检查本地网络！", Toast.LENGTH_LONG, true)
                    .setToastType(CWToast.TOAST_TYPE_ALERT).show();
        } else {
            if (mToast == null) {
                mToast = Toast.makeText(this, msg, duration);
            }
            mToast.setText(msg);
            mToast.setDuration(duration);
            mToast.show();
        }
    }

    protected void showInputDialog(final TextView tv) {
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.dialog_input, null);
        final EditText input = (EditText) view.findViewById(R.id.input);
        input.setInputType(tv.getInputType());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(tv.getHint().toString()).setView(view)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                tv.setText(input.getText().toString());
            }
        });
        builder.show();
        input.requestFocus();
    }

    protected void showConfirmDialog(String title, String message, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (TextUtils.isEmpty(title)) {
            builder
                    .setMessage(message)
                    .setNegativeButton("取消", null);
        } else {
            builder.setTitle(title)
                    .setMessage(message)
                    .setNegativeButton("取消", null);
        }
        builder.setPositiveButton("确定", listener);
        builder.show();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("BaseActivity", getClass().getSimpleName());
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void doShequClick() {
        String packageName = "com.bdhub.mth";
        String appName = "熟么";
        final Context context = this;
        Runnable notInstalledDo = new Runnable() {
            @Override
            public void run() {
                String downLink = "http://imtt.dd.qq.com/16891/CE886185FE5C65183CF46D14432A2673.apk?fsname=com.bdhub.mth_2.2.6_24.apk&csr=4d5s";
                IntentUtils.openBrowserToDownload(context, downLink);
            }
        };

        PackageUtils.openOutSideApp(context, packageName, appName, notInstalledDo);
    }


}
